﻿using Microsoft.Xaml.Behaviors;
using System.ComponentModel;
using Telerik.Windows.Controls;

namespace TruckScale.Behaviors
{
  public class ListBoxScrollToBottomBehavior : Behavior<RadListBox>
  {
    protected override void OnAttached()
    {
      base.OnAttached();
      //ICollectionView类型才有CollectionChanged事件
      ((ICollectionView)AssociatedObject.Items).CollectionChanged += ListBoxScrollToBottomBehavior_CollectionChanged;
    }

    protected override void OnDetaching()
    {
      base.OnDetaching();
      ((ICollectionView)AssociatedObject.Items).CollectionChanged -= ListBoxScrollToBottomBehavior_CollectionChanged;
    }

    private void ListBoxScrollToBottomBehavior_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
      if (AssociatedObject.HasItems)
      {
        AssociatedObject.ScrollIntoView(AssociatedObject.Items[AssociatedObject.Items.Count - 1]);
      }
    }
  }
}
